<?php

/**
 * 库存100JDK
 * @author chenyun
 */
namespace App\Service\VendorClient\ShopStock100;
use App\Service\Code\Normal;
use App\Service\TaskServer\TaskWorker;
use Service\AppService\IdService;

class ShopStock100Client
{
    private static $instance;
    private $account  = 'stock100';
    protected $config;
    protected $RouteMap = [
        'cancelOrder'       => '/returnOrder/returnOrderStatusChangeNotify',
    ];
    
    /**
     * 初始参数
     * @param obj $collection
     */
    public function __construct( $apiBody = [] ) 
    {
        $this->config = $apiBody;
    }

    /**
     * 订单取消状态推送
     * @param array $param
     */
    public function cancelOrder( $param = [] )
    {
        $orderInfo       = $param['orderLog'];
        //组装推送上游数据（30是拒绝，60是同意）
        $currentTime = time();
        $requestParam = [
            'method'    => 'cancelOrder',
            'data'      => [
                'appKey'           => $this->config['appKey'],
                'currentTime'       => $currentTime,
                'outReturnOrderSns'   => $orderInfo['outReturnOrderSn'],
                'status'            => 60,
            ],
        ];
        return $this->execute($requestParam);
    }
    //验签
    public function getSign($param = [])
    {
        ksort($param);
        $arr = "";
        foreach ($param as $k=>$v){
            $arr .= "{$k}={$v}&";
        }
        $str = $arr.$this->config['appSecret'];
        $str = strtoupper(md5($str));
        return $str;
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        if(empty($param['data']) ) {
            return Normal::returnCode(Normal::FAIL,"数据不能为空");
        }
        $method = $param['method'];
        $url = $this->config['url'].$this->RouteMap[$method];
        $param["data"]["sign"] = $this->getSign($param["data"]);
        $parameter = [
             [
                'tag'       => $this->account.'_'.$method,
                'uid'       => IdService::instance()->getOtherID(),
                'url'       => $url,
                'data'      => $param['data'],
                'method'    => 'post',
                'format'    => 'json',
                'header'    => [
                    "Content-Type:application/json",
                ],
        
            ],
        ];
        $resTask = TaskWorker::instance()->addTask($parameter);
        $resTask = current($resTask);
        $res     = $resTask['response']['result']; 
        $resHttp = @json_decode($res, true);
        if( isset($resHttp['code']) && $resHttp['code'] == Normal::SUC ) {
            return Normal::returnCode(Normal::SUC,"操作成功");
        }
        $message = isset($resHttp['message']) ? $resHttp['message'] : '请求失败';
        return Normal::returnCode(Normal::FAIL,$message);
    }
}
